import React, {
  Component,
} from 'react';
import PropTypes from 'prop-types';
import CopyToClipboard from 'react-copy-to-clipboard';

const QRCode = require('qrcode.react');

export default class ShareLinkDialog extends Component {
  constructor(props) {
    super(props);
    this.state = { ...props };
    this.close = this.close.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.display === true && this.state.display === false) {
      this.setState({ display: true });
    } else {
      this.setState({ display: nextProps.display });
    }
  }

  close() {
    if (this.props.onClosed) {
      this.props.onClosed();
    } else {
      this.setState({ display: false });
    }
  }

  render() {
    const isDisplay = this.state.display;
    return (
      <div className={`share-link-container ${isDisplay ? 'visible' : 'hidden'}`}>
        <div className="mask" onClick={this.close} />
        <div className="share-link-dlg">
          <div>
            <div className="caption">手机微信扫一扫</div>
            <div className="caption">快将 VR 大作分享到朋友圈</div>
            <div className="barcode">
              <QRCode
                value={this.props.link}
                size={224}
                fgColor="#0084FF"
                level="H"
              />
            </div>
            <div className="copy">
              <input
                type="text"
                readOnly
                ref={(input) => { this.linkText = input; }}
                value={this.props.link}
              />
              <CopyToClipboard text={this.props.link}>
                <button className="btn">复制</button>
              </CopyToClipboard>
            </div>
          </div>
          <span onClick={this.close} className="close" />
        </div>
      </div>
    );
  }
}

ShareLinkDialog.propTypes = {
  link: PropTypes.string,
  display: PropTypes.bool,
  onClosed: PropTypes.func,
};

ShareLinkDialog.defaultProps = {
  link: '',
  display: false,
};
